package com.gxwgy.wg2404.controller;

import com.gxwgy.wg2404.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 姚相国
 * @version 1.0
 * @className AdminDeleteUserServlet
 * @date 2024/12/18 15:36
 */
@WebServlet("/administrator/deleteUser")
public class AdminDeleteUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");

        // 检查是否已登录且为管理员
        if (username == null || (!"root".equals(username) && !"admin1".equals(username))) {
            // 如果未登录或非管理员，重定向到主页或错误页面
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }

        // 获取用户 ID
        String userIdStr = request.getParameter("id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            // 如果没有传递用户 ID，重定向到错误页面
            response.sendRedirect(request.getContextPath() + "/error.jsp");
            return;
        }

        int userId = Integer.parseInt(userIdStr);  // 将字符串转换为整数

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM users WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userId);

            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                // 删除成功，重定向到用户列表页面
                response.setContentType("text/html; charset=UTF-8");
                response.getWriter().println("<script>alert('用户删除成功！'); location.href='" + request.getContextPath() + "/admin/dashboard';</script>");
            } else {
                // 删除失败，重定向到错误页面
                response.sendRedirect(request.getContextPath() + "/error.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException("数据库操作失败", e);
        } finally {
            DBUtil.close(conn, ps, null);
        }
    }
}

